package com.lw.leetcode.arr.b;

/**
 * Created with IntelliJ IDEA.
 * arr
 * <p>
 * 2116. 判断一个括号字符串是否有效
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/9 16:58
 */
public class CanBeValid {

    public static void main(String[] args) {
        CanBeValid test = new CanBeValid();
        String a = "()";
        String b = "11";
        boolean b1 = test.canBeValid(a, b);
        System.out.println(b1);
    }

    public boolean canBeValid(String s, String locked) {
        int length = s.length();
        if (locked.length() % 2 != 0) {
            return false;
        }
        char[] chars = s.toCharArray();
        char[] lockeds = locked.toCharArray();
        boolean b = find(chars, lockeds);
        if (!b) {
            return false;
        }
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == '(') {
                chars[length - i - 1] = ')';
            } else {
                chars[length - i - 1] = '(';
            }
            lockeds[length - i - 1] = locked.charAt(i);
        }
        return find(chars, lockeds);
    }

    public boolean find(char[] chars, char[] lockeds) {
        int length = chars.length;
        int a = 0;
        int b = 0;
        int c = 0;
        for (int i = 0; i < length; i++) {
            if (lockeds[i] == '1') {
                if (chars[i] == '(') {
                    b++;
                } else {
                    c++;
                }
            } else {
                a++;
            }
            if (c > a + b) {
                return false;
            }
        }
        return b <= a + c;
    }

}
